<template>
  <div class="pages Purchase">
    <div class="pageLevel">
      <div class="operationBox tableSearch">
        <el-button type="primary" @click="goBack()" size="mini">返回</el-button>
        <el-button type="primary" @click="clickEdit()" size="mini" v-if="!isEdit && statuss=='0'&&setRole('修改')">修改</el-button>
        <el-button type="primary" @click="_handleSave()" size="mini" v-if="isEdit">保存</el-button>
      </div>

      <el-form class="tableSearch" v-if="isEdit">
        <el-form-item>
          <el-input v-model="goodsNameInput" disabled placeholder="请选择商品" size="small">
            <el-button type="primary" @click="clickSelectGoods" size="small" slot="append" :disabled="!isEdit">选择</el-button>
          </el-input>
        </el-form-item>
      </el-form>

      <div class="tableMain">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column type="index" label="序号" width="55"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" align="center" width="250"></el-table-column>
          <el-table-column prop="goodsPrice" label="商品单价" align="center" width="100">
            <template slot-scope="scope">
              <sd-input v-show="isEdit == true" :val.sync='scope.row.goodsPrice'></sd-input>
              <span v-show="isEdit == false">{{scope.row.goodsPrice}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="goodsUnit" label="采供单位" align="center"></el-table-column>
           <el-table-column prop="parameter" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item, index) in  scope.row.parameter" :key="index" v-if="item">
              <span>{{item.paramName}} :</span>
              <span>{{item.paramValue}} </span>
            </div>
          </template>
        </el-table-column>
          <el-table-column prop="barCode" label="商品条形码" align="center" width="100"></el-table-column>
          <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
          <!-- <el-table-column label="开始日期-结束日期" align="center" width="400" prop="dateRange">
            <template slot-scope="scope">
              <el-date-picker v-show="isEdit == true" size="small" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" unlink-panels v-model="scope.row.dateRange" type="daterange" clearable></el-date-picker>
              <span v-show="isEdit == false">{{scope.row.startDate}}-{{scope.row.endDate}}</span>
            </template>
          </el-table-column> -->
          <el-table-column prop="isFreight" label="是否含运费" align="center" width="100">
            <template slot-scope="scope">
              <el-switch v-show="isEdit == true" v-model="scope.row.isFreight" active-color="#13ce66" inactive-color="#ff4949" active-value='1' inactive-value='0'></el-switch>
              <span v-show="isEdit == false">{{scope.row.isFreight === '1' ? '是' : '否'}} </span>
            </template>
          </el-table-column>
          <el-table-column prop="freight" label="运费" align="center" width="100">
            <template slot-scope="scope">
              <sd-input v-if="scope.row.isFreight === '0'" v-show="isEdit == true" :val.sync='scope.row.freight'></sd-input>
              <span  v-show="isEdit == false">{{scope.row.freight}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" align="center" width="100" :formatter="Pricestatus"></el-table-column>
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button v-show="isEdit == true" type="text" @click="_handleCancel(scope.$index)" size="mini">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 商品选择弹出框 -->
    <el-dialog title="商品选择" class="addshopname" :visible.sync="dialogGood" :closeOnClickModal='false' :closeOnPressEscape='false' width="60%">
      <div class="operationBox tableSearch">
        <el-button size="mini" type="primary" @click="clickSelectGoodsConfirm">选择</el-button>
        <el-button size="mini" @click="dialogGood=false">取消</el-button>
      </div>
      <div class="tableSearch">
        <el-form size="mini">
          <el-form-item label="" label-width="0">
            <el-input clearable v-model="selectdata.keyword" placeholder="输入商品名称或编号"></el-input>
          </el-form-item>
          <el-form-item label="" label-width="15px">
            <el-button type="primary" @click="_handleSearchGood">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="goodArray" stripe border ref="multipleTablegood" tooltip-effect="dark" @selection-change="_handleChangeGood">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="purchaseUnit" label="采供单位" align="center"></el-table-column>
        <el-table-column prop="parameter" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item, index) in  scope.row.parameter" :key="index" v-if="item">
              <span>{{item.paramName}} :</span>
              <span>{{item.paramValue}} </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="barCode" label="商品条形码" align="center"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="pageDataGoods" :func="findGoodsListPage"></page-unit>
    </el-dialog>
  </div>
</template>
<script>
import util from "@/util";
import { mapState } from "vuex";
import sdInput from "@/components/SdInput";
import state from "@/util/state"; // 价格状态
import pageUnit from "@/components/Page";
import {
  findGoodsListPage, //商品弹出
  update,
  getDetailList
} from "@/api";
export default {
  components: { sdInput, pageUnit },
  computed: mapState(["sub", "power", "merchantId","linkName" ,"mobile"]),
  data () {
    return {
      Total:[],
      userName:"",
      templateId: "",
      statuss:"",
      isEdit: false,
      pageData: {
        pageSize: 20,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10, 20]
      },
      pageDataGoods: {
        pageSize: 20,
        currentPage: 1,
        totalItems: 0,
        pageSizeArr: [5, 10,20]
      },
      //商品输入框
      selectdata: {
        keyword: ""
      },
      tableData: [],
      dialogGood: false,
      selectionGood: [],
      goodArray: [],
      dateRange: new Date(),
      goodsNameInput: ""
    };
  },
  created () {
  },
  mounted () {
    this.templateId = util.getQuery().id;
    this.statuss = util.getQuery().status;
    this.getDetailList();
  },
  methods: {
                  //配置权限
    setRole (key) {
            return util.selectTitle(this.power, key)
        },
    Pricestatus: state.Pricestatus,
    goBack () {
      history.go(-1);
    },
    // 获取门店报货价格模板详情
    getDetailList () {
      let data = {
        templateId: this.templateId
      };
      getDetailList(data).then(res => {
        this.tableData = res.data;
        this.tableData.forEach(item=>{
          item.parameter=item.goodsSpec
        })
      });
    },
    // 点击修改
    clickEdit () {
      this.goodsNameInput = "请确认选择的商品";
      this.isEdit = true;
    },
    clickSelectGoods () {
      this.findGoodsListPage(this.pageDataGoods.pageSize, this.pageDataGoods.currentPage);
      this.dialogGood = true;
    },
    // 获取商品列表
    findGoodsListPage (pageSize, pageNum) {
      let data = {
        name: this.selectdata.keyword,
        pageSize: pageSize,
        pageNo: pageNum,
        shopId: this.merchantId,
        status: 0
      };
      findGoodsListPage(data).then(res => {
        this.goodArray = res.data.list;
        this.pageDataGoods.totalItems = res.data.total;
      });
    },
    // 商品搜索
    _handleSearchGood () {
      this.findGoodsListPage(this.pageDataGoods.pageSize, 1);
    },
    // 商品勾选
    _handleChangeGood (val) {
      if (val) {
        this.selectionGood = val;
      } else {
        this.selectionGood = [];
      }
    },
    // 选择商品
    clickSelectGoodsConfirm () {
      if (this.selectionGood.length === 0) {
        this.$message({
          type: "error",
          message: "请先选择商品!"
        });
      } {
        this.goodsNameInput = "请确认选择的商品";
         var self = this;
           if(this.linkName!=undefined ) {
             this.userName=this.linkName
           }else{
             this.userName=this.mobile
           }
          //  console.log(this.userName)
          //  return false
        this.selectionGood = this.selectionGood.map(item => {
          //遍历每次创建商品
          return {
            status: 0,
            goodsName: item.name,
            goodsId: item.id,
            goodsSpec: item.parameter,
            parameter:item.parameter,
            goodsUnit: item.goodsUnit,
            endDate:"",
            startDate:"",
            goodsPrice: 0,
            isFreight:'0',
            barCode:item.barCode,
            goodsCode:item.goodsCode,
            freight:"",
            primaryClassify:item.primaryClassify,
            createTimes: "",
            creater: self.userName,
            show: true,
            goodsUnit:item.purchaseUnit
          };
        });
        for (let i = 0; i < this.selectionGood.length; i++) {
          this.Total.unshift(this.selectionGood[i]); //多次创建商品集合
        }
         this.tableData = this.selectionGood.concat(this.tableData);
            var allArr = [];
        for (var i = 0; i < this.tableData.length; i++) {
          var flag = true;
          for (var j = 0; j < allArr.length; j++) {
            if (this.tableData[i].goodsId == allArr[j].goodsId) {
              flag = false;
            }
          }
          if (flag) {
            allArr.push(this.tableData[i]);
          }
        }
        this.tableData = allArr;
        this.dialogGood = false;
      }
    },
    // 删除某个选择的商品
    _handleCancel (index) {
      this.tableData.splice(index, 1);
      if (this.tableData.length == 0) {
        this.goodsNameInput = "请选择商品";
      }
    },
    _handleSave () {
      if (this.tableData.length == 0) {
        this.$message({
          type: "error",
          message: "商品列表不能为空!"
        });
      } else {
         for (let i = 0; i <  this.tableData.length; i++) {
               this.tableData[i].endDate="",
              this.tableData[i].startDate="",
               this.tableData[i].createTimes=""
              //  console.log(this.tableData[i].freight)
           if(this.tableData[i].isFreight==0 && this.tableData[i].freight==''){
             this.$message({
            type: "info",
            message: "不含运费时,运费不能为空"
          })
          return false
        }
      }
        let data = {
          orderPriceAgreementTemplate: {
            id: this.templateId
          },
          list: JSON.stringify(this.tableData)
        };
        update(data).then(res => {
             if(res.code==0){
          this.$message({
             type: 'error',
             message:res.msg
        });
        }else{
            this.$message({
          type: "success",
          message: "修改成功!"
        });
           history.back();
        }
        });
      }
    }
  }
};
</script>
